package com.pcbly.web.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.lang.reflect.Method;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.spring.BeanCreator;

import com.opensymphony.xwork2.ActionSupport;
import com.pcbly.web.Constants;
import com.pcbly.web.bean.dict.DictCategoryValueBean;
import com.pcbly.web.bean.system.LogBean;
import com.pcbly.web.bean.system.ProvinceCityBean;
import com.pcbly.web.bean.user.UserBean;
import com.pcbly.web.business.BaseService;
import com.pcbly.web.business.dict.DictCategoryCombService;
import com.pcbly.web.business.logger.LoggerService;
import com.pcbly.web.business.system.ProvinceCityService;

@SuppressWarnings("unchecked")
public class BaseAction<T> extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7864370281694511325L;

	public static final String CANCEL = "cancel";

	protected transient final Log log = LogFactory.getLog(getClass());

	private int page = 1;

	private int pageSize = Constants.DEFAULT_PAGE_SIZE;

	private String action = "index";

	protected BaseService<T> baseService;

	private LoggerService loggerService;

	private ProvinceCityService provinceCityService;

	private DictCategoryCombService dictCategoryCombService;

	protected String extendCustomer;

	protected String feedbackKeyAndValue;

	public String getFeedbackKeyAndValue() {
		return feedbackKeyAndValue;
	}

	public void setFeedbackKeyAndValue(String feedbackKeyAndValue) {
		this.feedbackKeyAndValue = feedbackKeyAndValue;
	}

	public String getExtendCustomer() {
		return extendCustomer;
	}

	public void setExtendCustomer(String extendCustomer) {
		this.extendCustomer = extendCustomer;
	}

	public void setDictCategoryCombService(
			DictCategoryCombService dictCategoryCombService) {
		this.dictCategoryCombService = dictCategoryCombService;
	}

	public void setProvinceCityService(ProvinceCityService provinceCityService) {
		this.provinceCityService = provinceCityService;
	}

	private String ajax = "json";

	private BeanCreator creator;

	private String id;

	private String myMessage;

	public static final String RESULT_AJAXJSON = "ajaxjson";

	public static final String RESULT_HTMLERROR = "htmlError";

	public static final String RESULT_ERROR = "error";

	public static final String RESULT_JSONSTRING = "jsonstring";

	protected String from = null;

	private String jsonString;

	public String getMyMessage() {
		return myMessage;
	}

	public void setMyMessage(String myMessage) {
		this.myMessage = myMessage;
	}

	public String getJsonString() {
		return jsonString;
	}

	public void setJsonString(String jsonString) {
		this.jsonString = jsonString;
	}

	public DictCategoryValueBean getDictCategoryValueBeanById(String id)
			throws Exception {
		return dictCategoryCombService.findDictCategoryValueBeanById(id);
	}

	public List<DictCategoryValueBean> findDictCategoryValueBeanListById(
			String id) throws Exception {
		return dictCategoryCombService.queryDictCategoryValueBeanById(id);
	}

	public List<ProvinceCityBean> findProvinceCityBeanListById(String parentId)
			throws Exception {
		return provinceCityService.findProvinceCityBeansByParentId(parentId);
	}

	public ProvinceCityBean getProvinceCityBeanById(String id) throws Exception {
		return provinceCityService.getProvinceCityBeanById(id);
	}

	public void setBaseService(BaseService<T> baseService) {
		this.baseService = baseService;
	}

	public String getUserId() {
		UserBean bean = (UserBean) getSession().getAttribute(
				Constants.USER_SESSION_KEY);
		String userId = null;
		if (bean == null) {
			userId = "089ED4F4-CEAD-6246-47AA-7599803D3EC5";
		} else {
			userId = bean.getId();
		}
		return userId;
	}

	public String getDwrUserId(HttpServletRequest request) {
		UserBean bean = (UserBean) request.getSession().getAttribute(
				Constants.USER_SESSION_KEY);
		String userId = null;
		if (bean == null) {
			userId = "089ED4F4-CEAD-6246-47AA-7599803D3EC5";
		} else {
			userId = bean.getId();
		}
		return userId;
	}

	public List<HashMap<String, String>> findCommnonDataBeanExt(
			String tableName, String id) throws Exception {

		return baseService.findCommnonDataBeanExt(tableName, id);
	}

	public String getDwrUserId() {
		WebContext context = WebContextFactory.get();
		HttpServletRequest request = context.getHttpServletRequest();
		return getDwrUserId(request);
	}

	public boolean checkReferer() {
		HttpServletRequest request = getRequest();
		String localhost = request.getServerName();
		if (request.getHeader("Referer") == null
				|| request.getHeader("Referer").indexOf(localhost) < 0) {
			return true;
		} else {
			return false;
		}
	}

	public BaseAction() {
		// TODO Auto-generated constructor stub
	}

	public String cancel() {
		if (!"list".equals(from)) {
			return "list";
		}
		return CANCEL;
	}

	public String home() throws Exception {

		return SUCCESS;
	}

	protected void saveMessage(String msg) {
		List messages = (List) getSession().getAttribute("messages");
		if (messages == null) {
			messages = new ArrayList();
		}
		messages.add(msg);
		getSession().setAttribute("messages", messages);
	}

	protected Map getConfiguration() {
		Map config = (HashMap) getSession().getServletContext().getAttribute(
				Constants.CONFIG);
		if (config == null) {
			return new HashMap();
		}
		return config;
	}

	protected String executeMethod(String method) throws Exception {
		Class[] c = null;
		Method m = getClass().getMethod(method, c);
		Object[] o = null;
		String result = (String) m.invoke(this, o);
		if (log.isDebugEnabled())
			log.debug(result);
		return result;
	}

	public void logDBAction(String action, String message) throws Exception {
		LogBean bean = new LogBean();
		bean.setMethodName(action);
		HttpServletRequest request = getRequest();
		// System.out.println(request.getRemoteAddr());
		bean.setLoginIp(request.getRemoteAddr());
		bean.setClassName(getClass().getName());
		// System.out.println(getClass().getName());
		bean.setMessage(message);
		bean.setUserId(getUserId());// need session
		bean.setCreateDate(new Date());
		// System.out.println(bean.getCreateDate());
		loggerService.saveLogger(bean);
		if (bean != null)
			bean = null;
	}

	public String save() throws Exception {
		long startTime = System.currentTimeMillis();
		String message = "";
		if (id == null || "".equals(id)) {
			message = "create new record";
		} else {
			message = "modify record" + id;
		}
		logDBAction("save", message);
		startTime = System.currentTimeMillis() - startTime;
		if (log.isDebugEnabled()) {
			log.debug("time ms:::::" + startTime);
			System.out.println("time ms:::::" + startTime);
		}
		return SUCCESS;
	}
	protected HttpSession getDwrSession(){
		WebContext context = WebContextFactory.get();
		HttpServletRequest request = context.getHttpServletRequest();
		return request.getSession();
	}
	public void logDWRDBAction(String action, String message) throws Exception {
		LogBean bean = new LogBean();
		bean.setMethodName(action);
		WebContext context = WebContextFactory.get();
		HttpServletRequest request = context.getHttpServletRequest();

		bean.setLoginIp(request.getRemoteAddr());
		bean.setClassName(this.getClass().getName());
		bean.setMessage(message);
		bean.setUserId(getDwrUserId(request));// need session
		bean.setCreateDate(new Date());
		loggerService.saveLogger(bean);
		if (bean != null)
			bean = null;
	}

	public String dwrBaseSave(String id) throws Exception {
		long startTime = System.currentTimeMillis();
		String message = "";
		if (id == null || "".equals(id)) {
			message = "create new record";
		} else {
			message = "modify record:" + id;
		}
		logDWRDBAction("dwrBaseSave", message);
		startTime = System.currentTimeMillis() - startTime;
		if (log.isDebugEnabled()) {
			log.debug("time ms:::::" + startTime);
			System.out.println("time ms:::::" + startTime);
		}
		return SUCCESS;
	}

	public String delete() throws Exception {
		long startTime = System.currentTimeMillis();
		String message = "delete record:" + id;
		logDBAction("delete", message);
		startTime = System.currentTimeMillis() - startTime;
		if (log.isDebugEnabled()) {
			log.debug("time ms:::::" + startTime);
			System.out.println("time ms:::::" + startTime);
		}
		return SUCCESS;
	}

	public String dwrBaseDelete(String id) throws Exception {
		long startTime = System.currentTimeMillis();
		String message = "";
		message = "delete record:" + id;
		logDWRDBAction("dwrBaseDelete", message);
		startTime = System.currentTimeMillis() - startTime;
		if (log.isDebugEnabled()) {
			log.debug("time ms:::::" + startTime);
			System.out.println("time ms:::::" + startTime);
		}
		return SUCCESS;
	}

	public String list() throws Exception {
		long startTime = System.currentTimeMillis();
		String message = "query record";
		logDBAction("list", message);
		startTime = System.currentTimeMillis() - startTime;
		if (log.isDebugEnabled()) {
			log.debug("time ms:::::" + startTime);
			System.out.println("time ms:::::" + startTime);
		}
		return SUCCESS;
	}

	public String update() throws Exception {
		long startTime = System.currentTimeMillis();
		String message = "update record" + id;
		logDBAction("update", message);
		startTime = System.currentTimeMillis() - startTime;
		if (log.isDebugEnabled()) {
			log.debug("time ms:::::" + startTime);
			System.out.println("time ms:::::" + startTime);
		}
		return SUCCESS;
	}

	public String modify() throws Exception {
		long startTime = System.currentTimeMillis();
		String message = "modify record" + id;
		logDBAction("modify", message);
		startTime = System.currentTimeMillis() - startTime;
		if (log.isDebugEnabled()) {
			log.debug("time ms:::::" + startTime);
			System.out.println("time ms:::::" + startTime);
		}
		return SUCCESS;
	}

	public String view() throws Exception {
		long startTime = System.currentTimeMillis();
		String message = "view record" + id;
		logDBAction("view", message);
		startTime = System.currentTimeMillis() - startTime;
		if (log.isDebugEnabled()) {
			log.debug("time ms:::::" + startTime);
			System.out.println("time ms:::::" + startTime);
		}
		return SUCCESS;
	}

	public String dwrBaseView(String id) throws Exception {
		long startTime = System.currentTimeMillis();
		String message = "";
		message = "dwrView record:" + id;
		logDWRDBAction("dwrBaseView", message);
		startTime = System.currentTimeMillis() - startTime;
		if (log.isDebugEnabled()) {
			log.debug("time ms:::::" + startTime);
			System.out.println("time ms:::::" + startTime);
		}
		return SUCCESS;
	}

	public String add() throws Exception {
		long startTime = System.currentTimeMillis();
		String message = "create new record";
		logDBAction("add", message);
		startTime = System.currentTimeMillis() - startTime;
		if (log.isDebugEnabled()) {
			log.debug("time ms:::::" + startTime);
			System.out.println("time ms:::::" + startTime);
		}
		return SUCCESS;
	}

	public String edit() throws Exception {
		long startTime = System.currentTimeMillis();
		String message = "edit record:" + id;
		logDBAction("edit", message);
		startTime = System.currentTimeMillis() - startTime;
		if (log.isDebugEnabled()) {
			log.debug("time ms:::::" + startTime);
			System.out.println("time ms:::::" + startTime);
		}
		return SUCCESS;
	}

	public String index() throws Exception {
		long startTime = System.currentTimeMillis();
		String message = "index records";
		logDBAction("index", message);
		startTime = System.currentTimeMillis() - startTime;
		if (log.isDebugEnabled()) {
			log.debug("time ms:::::" + startTime);
			System.out.println("time ms:::::" + startTime);
		}
		return SUCCESS;
	}

	protected void rendText(String content) throws IOException {
		HttpServletResponse response = getResponse();
		// response.setContentType("text/");
		response.getWriter().write(content);
	}

	protected HttpServletRequest getRequest() {

		return ServletActionContext.getRequest();
	}

	protected HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	protected HttpSession getSession() {
		return getRequest().getSession();
	}

	protected ServletContext getServletContext() {
		return ServletActionContext.getServletContext();
	}

	public int boolean2int(boolean value) {
		if (value) {
			return 1;
		} else {
			return 0;
		}
	}

	public boolean int2boolean(int value) {
		if (value == 0) {
			return false;
		} else {
			return true;
		}
	}

	public String getAction() {
		return action;
	}

	public void setAction(String action) {
		this.action = action;
	}

	public String getAjax() {
		return ajax;
	}

	public void setAjax(String ajax) {
		this.ajax = ajax;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public String htmEncode(String s) {
		StringBuffer stringbuffer = new StringBuffer();
		int j = s.length();
		for (int i = 0; i < j; i++) {

			char c = s.charAt(i);
			switch (c) {
			case 60:
				stringbuffer.append("&lt;");
				break;
			case 62:
				stringbuffer.append("&gt;");
				break;
			case 38:
				stringbuffer.append("&amp;");
				break;
			case 34:
				stringbuffer.append("&quot;");
				break;
			case 169:
				stringbuffer.append("&copy;");
				break;
			case 174:
				stringbuffer.append("&reg;");
				break;
			case 165:
				stringbuffer.append("&yen;");
				break;
			case 8364:
				stringbuffer.append("&euro;");
				break;
			case 8482:
				stringbuffer.append("&#153;");
				break;
			case 13:
				stringbuffer.append("<br>");
				break;
			// case 32:
			// stringbuffer.append("&nbsp;");
			// break;
			default:
				stringbuffer.append(c);
				break;
			}
		}
		return new String(stringbuffer.toString());
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	public BeanCreator getCreator() {
		return creator;
	}

	public void setCreator(BeanCreator creator) {
		this.creator = creator;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public void setLoggerService(LoggerService loggerService) {
		this.loggerService = loggerService;
	}

}
